package com.huffman.smart_picture.api.download.unsplash;

import com.huffman.smart_picture.api.download.ObtainImageQueryDto;
import com.huffman.smart_picture.api.download.ObtainImage;
import com.huffman.smart_picture.api.download.ObtainImageResult;
import com.huffman.smart_picture.common.exception.BusinessException;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.utils.ThrowUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class UnsplashImageApi implements ObtainImage {
    private static final String SEARCH_URL = "https://unsplash.com/s/photos/%s";

    @Override
    public List<ObtainImageResult> getImageUrls(ObtainImageQueryDto obtainImageQueryDto) {
        String searchKey = obtainImageQueryDto.getSearchKey();

        String url = String.format(SEARCH_URL, searchKey);
        Document document;
        try {
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorEnum.SYSTEM_ERROR, "获取页面失败,稍后再试");
        }
        List<ObtainImageResult> imageList = new ArrayList<>();
        Elements imageElements = document.getElementsByAttributeValue("data-testid", "photo-grid-list-figure");
        ThrowUtil.throwIf(imageElements == null, ErrorEnum.SYSTEM_ERROR, "获取元素失败");
        for (Element imageElement : imageElements) {

            Elements imgTag = imageElement.getElementsByAttributeValue("data-testid", "photo-grid-list-img");
            ThrowUtil.throwIf(imgTag == null, ErrorEnum.SYSTEM_ERROR, "获取图片失败");
            String src = imgTag.attr("src");
            // 取大图
            ObtainImageResult imageResult = new ObtainImageResult();
            imageResult.setUrl(src);
            imageList.add(imageResult);
        }

        return imageList;
    }

    public static void main(String[] args) {
//        ObtainUnsplashImagesApi obtainUnsplashImagesApi = new ObtainUnsplashImagesApi();
//        obtainUnsplashImagesApi.getImageUrls("科技");
    }
}
